<template>
  <div v-loading="loading">
    <DetailPanel :dataSource="data" :columns="columns" :buttons="buttons">
      <template slot="device">
        <span>
          所辖充电站/充电设备:{{
            `${this.data.stationNum || 0}/${this.data.deviceNum || 0}`
          }}<a
            class="merchant-detail-a"
            :href="`/#/device/stationList?id=${$route.params.userId}`"
            >查看详情>></a
          >
        </span>
      </template>
    </DetailPanel>
    <div
      class="panel"
      v-if="
        $store.getters.roleType === 'ADMIN' ||
        $store.getters.roleType === 'SELF_OPERATION_ADMIN'
      "
    >
      <div class="panel-header">微信进件</div>
      <TableSearch
        ref="tableSearch"
        :columns="tableColumns"
        :tableData="tableData"
        :pageNameDisplay="false"
      />
    </div>
    <ChangePaymentDlg
      :visible.sync="payMentDialogVisible"
      :defaultForm="defaultForm"
      v-if="payMentDialogVisible"
      @refresh="refresh"
    />
    <ResetPwdDlg
      :reset-pwd-visible.sync="resetPwdVisible"
      :merchant-id="merchantId"
      :type="resetPwdDlgType"
      :merchant-name="data.userName"
      :merchant-mobile="data.mobile"
    />
    <SettlementStatusDlg
      v-if="SSDlgVisible"
      :visible.sync="SSDlgVisible"
      :data="SSDlgData"
    />
  </div>
</template>
<script>
import DetailPanel from '@/components/DetailPanel'
import { queryMerchant, applymentMicroGetstate } from '@/api/user'
import ResetPwdDlg from './Dialogs/ResetPwdDlg'
import ChangePaymentDlg from './Dialogs/ChangePaymentDlg'
import { typeMap } from '@/utils/format'
import { cloneDeep, isString } from 'lodash'
import TableSearch from '@/components/TableSearch'
import SettlementStatusDlg from '@/components/SettlementStatusDlg'
import dayjs from 'dayjs'
import Big from 'big.js'

const APPLYMENT_STATE = {
  APPLYMENT_STATE_EDITTING: '编辑中',
  APPLYMENT_STATE_AUDITING: '审核中',
  APPLYMENT_STATE_REJECTED: '已驳回',
  APPLYMENT_STATE_TO_BE_CONFIRMED: '待账户验证',
  APPLYMENT_STATE_TO_BE_SIGNED: '待账户验证',
  APPLYMENT_STATE_SIGNING: '开通权限中',
  APPLYMENT_STATE_FINISHED: '已完成',
  APPLYMENT_STATE_CANCELED: '已作废',
}

const paymentType = {
  '-1': '无支付权限',
  0: '微信公众号',
  1: '微信APP',
  2: '支付宝',
  3: '云闪付支付',
  4: '微信小程序',
  5: '银联-微信APP',
  6: '银联-微信公众号',
  7: '银联-微信小程序',
  8: '普通商户-微信公众号',
  9: '普通商户-微信APP',
  10: '普通商户-微信小程序',
  11: '支付宝小程序',
  13: '移动话费',
}

export default {
  name: 'UserDetail',
  components: {
    DetailPanel,
    ResetPwdDlg,
    TableSearch,
    SettlementStatusDlg,
    ChangePaymentDlg,
  },
  mounted() {
    this.getMerchantDetails()
  },
  methods: {
    refresh() {
      this.getMerchantDetails()
    },
    getMerchantDetails() {
      if (!this.$route.params.userId) return

      this.loading = true
      queryMerchant({ id: parseInt(this.$route.params.userId) })
        .then((res) => {
          // this.data = res
          this.setColumns(res)
          this.setPaymentStatus(res)
          this.data = res
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.loading = false
        })

      if (
        this.$store.getters.roleType === 'ADMIN' ||
        this.$store.getters.roleType === 'SELF_OPERATION_ADMIN'
      ) {
        this.getWxStatus(false)
      }

      this.merchantId = this.$route.params.userId
    },
    getWxStatus(bool) {
      return false
      this.loading = true
      applymentMicroGetstate({
        submitUserId: this.$route.params.userId,
      })
        .then((res) => {
          let list = [
            {
              name: '小微商户',
              statusEesc: '',
              status: '',
            },
          ]
          if (
            Object.prototype.hasOwnProperty.call(res, 'applyment_state_msg')
          ) {
            // 字段兼容，新接口
            res.applyment_state_desc = APPLYMENT_STATE[res.applyment_state]
          }

          list[0].statusEesc = res.applyment_state_desc
          list[0].status = res.applyment_state

          this.tableData = {
            list,
            totalCount: 1,
          }

          if (bool) {
            this.SSDlgVisible = true
            this.SSDlgData = res
          }
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.loading = false
        })
    },
    tranformChannelsToArray(paymentChannels) {
      if (!isString(paymentChannels)) return []
      return paymentChannels.split(',').map((item) => item)
    },
    setPaymentStatus(res) {
      let tempForm = {
        ...this.defaultForm,
        ...res,
      }

      this.defaultForm = tempForm
    },
    insertColumns(target, columnsArr, sentryVal) {
      let sentryIndex = target.findIndex((item) => item.value === sentryVal)
      if (sentryIndex < 0) return

      let insertColumnsArr = columnsArr.reverse()

      insertColumnsArr.forEach((item) => {
        target.splice(sentryIndex + 1, 0, item)
      })
    },
    setColumns(res) {
      const weixinCols = [
        {
          label: '子商户APPID',
          value: 'weixinSubAppid',
        },
        {
          label: '微信子商户号',
          value: 'weixinSubMchId',
        },
        {
          label: '微信退款授权',
          value: 'refund',
          formatter: (item) => {
            return item.refund ? '授权' : '未授权'
          },
        },
      ]

      const bankCols = [
        {
          label: '银联门店ID',
          value: 'unionpayOpenId',
        },
        {
          label: '银联支付秘钥',
          value: 'unionpayOpenKey',
        },
        {
          label: '银联商户主密码',
          value: 'unionpayShopPass',
        },
        {
          label: '银联退款授权',
          value: 'refund',
          formatter: (item) => {
            return item.refund ? '授权' : '未授权'
          },
        },
      ]

      const cardAliasNoCol = [
        {
          label: '支付宝商户银行卡号',
          value: 'cardAliasNo',
        },
      ]

      const aliLoginNameCol = [
        {
          label: '支付宝账号',
          value: 'aliLoginName',
        },
      ]

      const aliExternalIdCol = [
        {
          label: '支付宝二级商户号',
          value: 'aliExternalId',
        },
      ]

      const smsMchIdCol = [
        {
          label: '移动支付商户ID',
          value: 'smsMchId',
        },
      ]

      const paymentChannelsCol = [
        {
          label: '支付方式',
          value: 'paymentChannels',
          formatter(item) {
            let str = ''
            if (!item.paymentChannels) return
            item.paymentChannels.split(',').forEach((num) => {
              if (paymentType[num]) {
                str = str + paymentType[num] + ', '
              }
            })
            str = str.substring(0, str.lastIndexOf(','))
            return str
          },
        },
      ]

      const userPathCol = [
        {
          label: '商户路径',
          value: 'userPath',
        },
      ]

      let paymentArr = this.tranformChannelsToArray(res.paymentChannels)

      const tempColumns = cloneDeep(this.defaultColumns)

      if (Array.isArray(paymentArr)) {
        if (
          paymentArr.findIndex((item) => item == '0') != -1 ||
          paymentArr.findIndex((item) => item == '1') != -1 ||
          paymentArr.findIndex((item) => item == '4') != -1
        ) {
          this.insertColumns(tempColumns, weixinCols, 'createTime')
        } else if (
          paymentArr.findIndex((item) => item == '5') != -1 ||
          paymentArr.findIndex((item) => item == '6') != -1 ||
          paymentArr.findIndex((item) => item == '7') != -1
        ) {
          this.insertColumns(tempColumns, bankCols, 'createTime')
        }
      }

      if (res.cardAliasNo) {
        this.insertColumns(tempColumns, cardAliasNoCol, 'createTime')
      }

      if (res.aliLoginName) {
        this.insertColumns(tempColumns, aliLoginNameCol, 'createTime')
      }

      if (res.aliExternalId) {
        this.insertColumns(tempColumns, aliExternalIdCol, 'createTime')
      }

      if (res.smsMchId) {
        this.insertColumns(tempColumns, smsMchIdCol, 'createTime')
      }

      if (res.paymentChannels) {
        this.insertColumns(tempColumns, paymentChannelsCol, 'createTime')
      }

      if (res.userPath) {
        this.insertColumns(tempColumns, userPathCol, 'creatTime')
      }

      this.columns = tempColumns
    },
  },
  data() {
    return {
      loading: false,
      tableData: {},
      SSDlgData: {},
      resetDlgKey: 1,
      SSDlgVisible: false,
      userType: '',
      tableColumns: [
        {
          label: '进件类型',
          prop: 'name',
        },
        {
          label: '状态',
          prop: 'statusEesc',
          formatter: (row) => {
            return row.statusEesc || '-'
          },
        },
        {
          label: '操作',
          buttons: [
            {
              label: '添加',
              disabled: (row) => {
                return (
                  row.status == 'FINISH' ||
                  row.status == 'APPLYMENT_STATE_FINISHED' ||
                  row.status == '99'
                )
              },
              click: () => {
                this.$router.push(`/user/wxPay/${this.$route.params.userId}`)
              },
              resouceId:
                '/web/user-management/merchant-management/merchantDetail/添加',
            },
            {
              label: '获取状态',
              click: () => {
                this.getWxStatus(true)
              },
              disabled: (row) => {
                return !row.status
              },
              resouceId:
                '/web/user-management/merchant-management/merchantDetail/获取状态',
            },
            // {
            //   label: '更改银行卡',
            //   click: () => {},
            //   resouceId: ''
            // },
          ],
        },
      ],
      merchantId: '',
      resetPwdVisible: false,
      resetPwdDlgType: '',
      form: {},
      defaultForm: {
        paymentChannels: '',
        small: false,
        jiesuan: '支付宝',
      },
      rules: {},
      buttons: [
        {
          label: '重置密码',
          type: 'primary',
          click: () => {
            this.resetPwdDlgType = 'update'
            this.resetPwdVisible = true
          },
          resourceId:
            '/web/user-management/merchant-management/merchantDetail/重置密码',
        },
        {
          label: '删除商户',
          type: 'warning',
          click: () => {
            this.resetPwdDlgType = 'remove'
            this.resetPwdVisible = true
          },
          resourceId:
            '/web/user-management/merchant-management/merchantDetail/删除商户',
        },
        {
          label: '修改支付信息',
          type: 'success',
          click: () => {
            this.payMentDialogVisible = true
          },
          resourceId:
            '/web/user-management/merchant-management/merchantDetail/修改支付信息',
        },
      ],
      payMentDialogVisible: false,
      data: {},
      defaultColumns: [
        {
          label: '商户名',
          value: 'userName',
        },
        {
          label: '手机号',
          value: 'mobile',
        },
        {
          label: '客服电话',
          value: 'serviceMobile',
        },
        {
          label: '管理员姓名',
          value: 'name',
        },
        {
          label: '分账比例',
          value: 'splitValue',
          formatter: (item) => {
            return `${Big(item.splitValue).times(100)}%`
          },
          ifRender: (item) => {
            return item.type === 'SELF_OPERATION_MERCHANT'
          },
        },
        {
          label: '平台分账模式',
          value: 'splitCalcMethod',
          formatter: (item) => {
            return item.splitCalcMethod == 'NO_ELECTRICITY'
              ? '成本前'
              : item.splitCalcMethod == 'WITH_ELECTRICITY'
              ? '成本后'
              : ''
          },
        },
        {
          label: '商户类别',
          // value: 'type',
          formatter: (item) => {
            return typeMap.userType[item.type] || ''
          },
        },
        {
          label: '注册时间',
          value: 'createTime',
          formatter: (item) => {
            if (item.createTime) {
              return dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss')
            }
          },
        },
        {
          slot: 'device',
        },
      ],
      columns: [],
    }
  },
}
</script>
<style lang="scss" scoped>
.merchant-detail-update_dialog_label {
  font-weight: bold;
  width: 100px;
  text-align: right;
}

.merchant-detail-a {
  color: #1a6deb;
}

.merchant-detail-show_sub_merchant {
  border-bottom: 1px solid #000;
}

.merchant-detail-payment_bottom {
  border-bottom: 1px solid #000;
}
</style>
